import logging
import sys

LOG_LEVEL_DICT = {'debug': logging.DEBUG, 'info': logging.INFO, 'error': logging.ERROR}


class AutomationLogger():
    _we_are_one = {}
    _configured = False

    @property
    def logger(self):
        return self._logger

    def __init__(self):

        self.__dict__ = self._we_are_one

    def setUp(self, log_level='debug'):

        if not self._configured:
            if log_level.lower() not in LOG_LEVEL_DICT.keys():
                raise ValueError(f'Log level {log_level} not valid.'
                                 f'  Valid log levels are {LOG_LEVEL_DICT.keys()}')

            self._logger = logging.getLogger(__name__)
            self.set_log_level(log_level)
            self.logger.propagate = False
            self._stream_handler = logging.StreamHandler(sys.stdout)
            self._formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', '%H:%M:%S')
            self._stream_handler.setFormatter(self._formatter)
            self.logger.addHandler(self._stream_handler)
            self._configured = True
        else:
            self.logger.debug(f'Logger already configured, will not configure again')

    def set_log_level(self, log_level):

        if log_level.lower() not in LOG_LEVEL_DICT.keys():
            raise ValueError(f'Log level {log_level} not valid.'
                             f'  Valid log levels are {LOG_LEVEL_DICT.keys()}')
        self.logger.debug(f'Setting log level to {LOG_LEVEL_DICT[log_level.lower()]}')
        self.logger.setLevel(LOG_LEVEL_DICT[log_level.lower()])

    def tearDown(self):

        self.logger.debug('Flushing log & stream handlers and removing them')
        self._stream_handler.flush()
        self._stream_handler.close()
        self.logger.removeHandler(self._stream_handler)
        self._configured = False
